//
//  OAApprovalSubmitViewController.m
//  ERP
//
//  Created by goldeney on 15/3/26.
//  Copyright (c) 2015年 ShangHai Goldeneye Techonology Co.,Ltd. All rights reserved.
//

#import "OAApprovalSubmitViewController.h"

#import "GEPickerTextField.h"
#import "GEObjectButton.h"
#import "GEInputTableViewCell.h"
#import "AutoTextTableViewCell.h"

#import "ServiceConnect.h"
#import "UserLoginNSCoding.h"
#import "NSKeyedArchiverUserLogin.h"
#import "NSDictionary+DataFormat.h"

@interface OAApprovalSubmitViewController()

@property (nonatomic,strong) NSDictionary *approvalMainInfo;
@property (nonatomic, strong) NSMutableArray *approvalTypeArray;
@property (nonatomic, strong) NSMutableArray *approvalData;

@property (nonatomic,strong) NSDictionary *approvalNodeInfo;
@property (nonatomic,strong) NSDictionary *approvalNextNodeInfo;

@end


@implementation OAApprovalSubmitViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
        [self setTitle: @"申请审批"];
    }
    return self;
}

- (void)getPassingParameter:(id)object
{
    NSArray *objectArray = object;
    self.approvalMainInfo = objectArray[0];
    self.approvalNodeInfo = objectArray[1];
    self.approvalNextNodeInfo = objectArray[2];
    
    //判断节点是否是执行
    //tnodetype:节点类型0-审批人1-执行人
    if(!self.approvalNodeInfo) return;
    self.approvalTypeArray = [NSMutableArray array];
    NSInteger nodeType = [[self.approvalNodeInfo objectFormatForKey:@"tnodetype"] integerValue];
    if(nodeType == 1){
        NSMutableDictionary *approvalTypeDic = [NSMutableDictionary dictionary];
        [approvalTypeDic setObject:@3 forKey:@"value"];
        [approvalTypeDic setObject:@"执行" forKey:@"key"];
        [self.approvalTypeArray addObject:approvalTypeDic];
        
    } else {
        NSMutableDictionary *approvalTypeDic = [NSMutableDictionary dictionary];
        [approvalTypeDic setObject:@1 forKey:@"value"];
        [approvalTypeDic setObject:@"同意" forKey:@"key"];
        [self.approvalTypeArray addObject:approvalTypeDic];
        
        NSMutableDictionary *approvalTypeDicTwo = [NSMutableDictionary dictionary];
        [approvalTypeDicTwo setObject:@2 forKey:@"value"];
        [approvalTypeDicTwo setObject:@"不同意" forKey:@"key"];
        [self.approvalTypeArray addObject:approvalTypeDicTwo];
        
    }
    
    //按钮添加
    if(nodeType == 1){
        UIBarButtonItem *leftButton = [[UIBarButtonItem alloc] initWithTitle:@"执行" style:UIBarButtonItemStyleDone target:self
                                                                      action:@selector(approvalSubmit:)];
        self.navigationItem.rightBarButtonItem = leftButton;
    } else {
        UIBarButtonItem *leftButton = [[UIBarButtonItem alloc] initWithTitle:@"提交" style:UIBarButtonItemStyleDone target:self
                                                                      action:@selector(approvalSubmit:)];
        self.navigationItem.rightBarButtonItem = leftButton;
    }
    
    //获取用户信息
    UserLoginNSCoding *userInfo = [NSKeyedArchiverUserLogin getUserLoginData];
    NSMutableArray *approval = [NSMutableArray array];
    
    [self addApprovalInfoKey:@"serialnumber" toKey:@"流  水  号：" defaults:@"未知" format:nil form:_approvalMainInfo toArray:approval];
    [self addApprovalInfoKey:@"templatename" toKey:@"申请名称：" defaults:@"未知" format:nil form:_approvalMainInfo toArray:approval];
    [self addApprovalInfoKey:@"sponsorid" toKey:@"发  起  人：" defaults:@"未知" format:nil form:_approvalMainInfo toArray:approval];
    [self addApprovalInfoKey:@"creationTime" toKey:@"发起时间：" defaults:@"未知" format:nil form:_approvalMainInfo toArray:approval];
    [self addApprovalInfoKey:@"" toKey:@"审批对象：" defaults:userInfo.username format:nil form:_approvalMainInfo toArray:approval];
    self.approvalData = approval;
}

- (void)addApprovalInfoKey:(id)key toKey:(id)tokey defaults:(id)def format:(id)formatText
                      form:(NSDictionary*)dic toArray:(NSMutableArray*)array
{
    id value = [dic objectFormatForKey:key];
    if (!def) def = @"";
    
    if (!value){
        value = def;
    } else if (formatText) {
        value = [NSString stringWithFormat:formatText,value];
    }
    
    NSDictionary *valueDic = [NSDictionary dictionaryWithObject:value forKey:tokey];
    [array addObject:valueDic];
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    
    self.tableView.tableHeaderView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, SuperWidth, 10)];
    self.tableView.tableFooterView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, SuperWidth, 10)];
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark
#pragma mark - 发送消息

- (void)approvalSubmit:(id)selector
{
    //关闭键盘
    [[[UIApplication sharedApplication] keyWindow] endEditing:YES];
    
    //审批状态
    GEPickerTextField *textFieldOne = [self getCellClass:[UITextField class] pathForRow:0 inSection:1];
    NSDictionary *spstType = textFieldOne.selectData;
    
    //印章信息
    //GEPickerTextField *textFieldTwo = [self getCellClass:[UITextField class] pathForRow:1 inSection:1];
    //NSDictionary *tjyzType = textFieldTwo.selectData;
    
    if (!(spstType && spstType.count>0)) {
        [self showAlertView:@"请选择审批状态"];
    }
//    else if (!(tjyzType && tjyzType.count>0)){
//        [self showAlertView:@"请选择印章类型"];
//    }
    else {
        //发送消息
        [self getNetWorkDataApprovalSubmit];
    }
}

- (void)getNetWorkDataApprovalSubmit
{
    //获取用户信息
    UserLoginNSCoding *userInfo = [NSKeyedArchiverUserLogin getUserLoginData];
    
    //审批状态
    GEPickerTextField *textFieldOne = [self getCellClass:[UITextField class] pathForRow:0 inSection:1];
    NSDictionary *spstType = textFieldOne.selectData;
    NSString *ApprovalStatus = [spstType objectFormatForKey:@"value"];
    
    //印章信息
    GEPickerTextField *textFieldTwo = [self getCellClass:[UITextField class] pathForRow:1 inSection:1];
    NSDictionary *tjyzType = textFieldTwo.selectData;
    NSString *sealPath = [tjyzType objectFormatStringForKey:@"sealPath"];
    
    //审批消息
    UITextView *affixToField = [self getCellClass:[UITextView class] pathForRow:0 inSection:2];
    NSString *affixTo = [affixToField.text stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];
    
    NSString *serialNumber = [self.approvalMainInfo objectFormatStringForKey:@"serialnumber"];
    id processType = [self.approvalMainInfo objectFormatForKey:@"processtype"];
    
    //判断有无当前节点
    id currNodeId = nil;
    id currNodeType = nil;
    if (self.approvalNodeInfo && self.approvalNodeInfo.count>0) {
        currNodeId = [self.approvalNodeInfo objectFormatForKey:@"nodeid"];
        currNodeType = [self.approvalNodeInfo objectFormatForKey:@"tnodetype"];
    } else {
        currNodeId = [NSNumber numberWithInteger:0];
        currNodeType = [NSNumber numberWithInteger:0];
    }
    
    //判断有无下一个节点
    id nextNodeId = nil;
    id nextNodeType;
    if (self.approvalNextNodeInfo && self.approvalNextNodeInfo.count>0) {
        nextNodeId = [self.approvalNextNodeInfo objectFormatForKey:@"nodeid"];
        nextNodeType = [self.approvalNextNodeInfo objectFormatForKey:@"tnodetype"];
    } else {
        nextNodeId = [NSNumber numberWithInteger:0];
        nextNodeType = [NSNumber numberWithInteger:0];
    }
    
    ServiceParametModel *wbsModel = [[ServiceParametModel alloc] init];
    [wbsModel setValue:userInfo.Id forKey:@"userid"];
    [wbsModel setValue:serialNumber forKey:@"serialNumber"];//流水号
    [wbsModel setValue:processType forKey:@"processType"];//流程类型
    [wbsModel setValue:currNodeId forKey:@"currNodeId"];//当前节点
    [wbsModel setValue:currNodeType forKey:@"currNodeType"];//当前节点类型
    [wbsModel setValue:ApprovalStatus forKey:@"ApprovalStatus"];//审批状态
    [wbsModel setValue:nextNodeId forKey:@"nextNodeId"];//下一个审批节点id
    [wbsModel setValue:nextNodeType forKey:@"nextNodeType"];//下一个审批节点类型
    [wbsModel setValue:affixTo forKey:@"affixTo"];//审批意见
    [wbsModel setValue:sealPath forKey:@"sealPath"];//印章路径
    
    ServiceConnect *content = [[ServiceConnect alloc] initWithMethodName:@"OA_Submit_Approval" dataArray:wbsModel];
    [content showMBProgressHUD:self.navigationController labelText:@"正在提交"];
    [content startConnectNetworkCompleted:^(ServiceResultModel *result, NSDictionary *userInfo) {
        if(result.resultArray && result.resultArray.count>0){
            //result：返回结果(1成功，0失败)
            NSDictionary *resultArray = [result.resultArray firstObject];
            NSInteger result = [[resultArray objectFormatForKey:@"result"] integerValue];
            if (result == 0) [self showAlertView:@"提交失败，请重新尝试"];
            else [self successUpLoadBriefcase];
            
        } else {
            [self showAlertView:@"提交失败，请重新尝试"];
        }
    } failed:^(NSError *error, NSDictionary *userInfo) {
        NSLog(@"==failed===%@",error);
        [self showAlertView:@"审批出错了，请重新尝试"];
        
    } abnormal:^(NSError *error, NSDictionary *userInfo) {
        NSLog(@"===abnormal==%@",error);
        [self showAlertView:@"没有连接网络，请检查网络是否连接"];
    }];
}

#pragma mark -
#pragma mark Get UITableViewCell

- (id)getCellClass:(Class)mClass pathForRow:(NSInteger)row inSection:(NSInteger)section
{
    NSIndexPath *indexPath = [NSIndexPath indexPathForRow:row inSection:section];
    UITableViewCell *tableCell = [self.tableView cellForRowAtIndexPath:indexPath];
    for (id view in tableCell.contentView.subviews) {
        if ([view isKindOfClass:mClass]) {
            return view;
        }
    }
    return nil;
}

- (void)successUpLoadBriefcase
{
    UIAlertView *alert=[[UIAlertView alloc] initWithTitle:@"温馨提示" message:@"审批成功" delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil];
    alert.alertViewStyle=UIAlertViewStyleDefault;
    [alert show];
}


#pragma mark
#pragma mark - UIAlertViewDelegate

- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    if(self.backResultDelagate)
        [self.backResultDelagate backResultDataKey:self.key dataValue:nil];
    [self.navigationController popViewControllerAnimated:YES];
}

#pragma mark - UIAlertView

- (void)showAlertView:(NSString*)message
{
    UIAlertView *alert=[[UIAlertView alloc] initWithTitle:@"温馨提示" message:message delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil];
    alert.alertViewStyle=UIAlertViewStyleDefault;
    [alert show];
}

#pragma mark
#pragma mark - UITableViewDataSource

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 3;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if(section == 1) return 2;
    else return 1;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSString *CellIdentifier = [NSString stringWithFormat:@"OAUploadMessageViewCell%ld%ld",indexPath.section,indexPath.row];
    if(indexPath.section == 0){
        AutoTextTableViewCell *cell = [[AutoTextTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"AutoTextTableViewCell"];
        [cell setDataArray:self.approvalData];
        return cell;
        
    } else if(indexPath.section == 1){
        GEInputTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
        if (cell != nil) return cell;
        
        if (indexPath.row == 0) {
            //审批状态
            cell = [[GEInputTableViewCell alloc] initWithSelectReuseIdentifier:CellIdentifier model:nil];
            cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
            cell.titleName = @"审批状态";
            cell.placeholder = @"请选择审批状态";
            cell.isMark = YES;
            [cell setIsChangeWidth:YES];
            
        } else if (indexPath.row == 1) {
            //印章选择
            UserLoginNSCoding *userInfo = [NSKeyedArchiverUserLogin getUserLoginData];
            ServiceParametModel *model = [[ServiceParametModel alloc] init];
            model.methodName = @"OA_getUserSeal";
            [model setValue:userInfo.Id forKey:@"userid"];
            
            cell = [[GEInputTableViewCell alloc] initWithSelectReuseIdentifier:CellIdentifier model:model];
            cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
            cell.titleName = @"添加印章";
            cell.placeholder = @"请选择印章类型";
            cell.isMark = NO;
            [cell setIsChangeWidth:YES];
        }
        return cell;
        
    } else if(indexPath.section == 2){
        UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
        if (cell == nil) {
            cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
            cell.accessoryType = UITableViewCellAccessoryNone;
            UITextView *field = [[UITextView alloc] initWithFrame:CGRectMake(5, 5, cell.contentView.frame.size.width - 25, 140)];
            field.font = [UIFont systemFontOfSize:15.0];
            field.textColor = [UIColor darkGrayColor];
            field.textAlignment = NSTextAlignmentLeft;
            [cell.contentView addSubview:field];
        }
        return cell;
    }
    
    return nil;
}

#pragma mark
#pragma mark - UITableViewDelegate

-(void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath
{
    if ([tableView respondsToSelector:@selector(setSeparatorInset:)]) {
        [tableView setSeparatorInset:UIEdgeInsetsZero];
    }
    
    if ([tableView respondsToSelector:@selector(setLayoutMargins:)]) {
        [tableView setLayoutMargins:UIEdgeInsetsZero];
    }
    
    if ([cell respondsToSelector:@selector(setLayoutMargins:)]) {
        [cell setLayoutMargins:UIEdgeInsetsZero];
    }
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, SuperWidth, 30)];
    view.backgroundColor = [UIColor whiteColor];
    UILabel *lable = [[UILabel alloc] initWithFrame:CGRectMake(5, 0, SuperWidth - 10, 29.5)];
    lable.textColor = [UIColor darkGrayColor];
    lable.font = [UIFont boldSystemFontOfSize:15];
    [view addSubview:lable];
    
    if (section == 0) {
        lable.text = @"审批基本信息";
    } else if(section == 1){
        lable.text = @"审批处理";
    } else if(section == 2){
        lable.text = @"填写审批意见";
    }
    
    UIView *lineView = [[UIView alloc] initWithFrame:CGRectMake(0, 29, SuperWidth, 1)];
    lineView.backgroundColor = [UIColor groupTableViewBackgroundColor];
    [view addSubview:lineView];
    
    return view;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return 30;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section == 0) {
        AutoTextTableViewCell *cell = [[AutoTextTableViewCell alloc] init];
        [cell setDataArray:self.approvalData];
        return cell.contentView.frame.size.height;
        
    } else if (indexPath.section == 1) return 44;
    else return 145;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    //键盘事件处理
    if(indexPath.section == 1) {
        UITableViewCell *tableCell = [tableView cellForRowAtIndexPath:indexPath];
        for (id view in tableCell.contentView.subviews) {
            if ([view isKindOfClass:[UITextField class]]) {
                UITextField *textField = view;
                [textField becomeFirstResponder];
            }
        }
    }
    
    //审批状态
    if(indexPath.section == 1 && indexPath.row == 0) {
        GEInputTableViewCell *geViewCell = (GEInputTableViewCell*)[tableView cellForRowAtIndexPath:indexPath];
        NSDictionary *QDDJ = [NSDictionary dictionaryWithObject:@"%@" forKey:@"key"];
        [geViewCell setPickerTextFieldComponents:self.approvalTypeArray keyValue:@[QDDJ]];
    }
    
    //添加印章
    else if(indexPath.section == 1 && indexPath.row == 1){
        GEInputTableViewCell *geViewCell = (GEInputTableViewCell*)[tableView cellForRowAtIndexPath:indexPath];
        NSArray *resultArray = geViewCell.objectData;
        
        if (resultArray) {
            NSDictionary *QDDJ = [NSDictionary dictionaryWithObject:@"%@" forKey:@"sealName"];
            [geViewCell setPickerTextFieldComponents:resultArray keyValue:@[QDDJ]];
        } else {
            [geViewCell reloadData];
        }
    }
    
}

@end
